﻿using System;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
using System.Reflection;
using System.Collections.Generic;

namespace WSOAMOBIMIDWARE
{
    public class HttpService
    {
        /// <summary>
        /// 发送Http请求
        /// </summary>
        public static HttpResponse HttpRequest(string url, string method, string postData, Encoding encoding, WSOA_Cookie[] cookies)
        {
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Stream requestStream = null;
            Stream responseStream = null;
            StreamReader streamReader = null;
            byte[] bytes = null;
            string returnStr = string.Empty;
            HttpResponse httpResponse;

            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);

                if (cookies != null)
                {
                    for (int i = 0; i < cookies.Length; i++)
                    {
                        request.Headers.Add(cookies[i].name, cookies[i].value);
                    }
                }


                //以下是发送的http头，随便加，其中referer挺重要的，有些网站会根据这个来反盗链  

                //禁止重定向
                request.AllowAutoRedirect = false;

                //保持连接
                request.KeepAlive = true;

                //上面的http头看情况而定，但是下面俩必须加  
                request.ContentType = "application/x-www-form-urlencoded";

                //提交请求方式
                request.Method = method;
                if (!string.IsNullOrEmpty(postData))
                {
                    //postDataStr即为发送的数据  
                    bytes = encoding.GetBytes(postData);
                    request.ContentLength = bytes.Length;

                    //初始化请求数据流
                    requestStream = request.GetRequestStream();
                    requestStream.Write(bytes, 0, bytes.Length);
                }

                //获取返回数据
                response = (HttpWebResponse)request.GetResponse();
                responseStream = response.GetResponseStream();

                //将返回数据解析为字符串
                streamReader = new StreamReader(responseStream, encoding);
                returnStr = streamReader.ReadToEnd();

                httpResponse = new HttpResponse(true, response.Headers.Get("Set-Cookie"), returnStr);
            }
            catch (Exception e)
            {
                httpResponse = new HttpResponse(false, e.Message);
            }
            finally
            {
                bytes = null;
                returnStr = string.Empty;
                //关闭连接
                if (streamReader != null) streamReader.Close();
                if (responseStream != null) responseStream.Close();
                if (requestStream != null) requestStream.Close();
            }
            return httpResponse;
        }
        /// <summary>
        /// 发送Http请求
        /// </summary>
        public static HttpResponse HttpRequestFile(string url, string method, string postData, Encoding encoding, WSOA_Cookie[] cookies)
        {
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Stream requestStream = null;
            StreamReader streamReader = null;
            Stream responseStream = null;
            byte[] bytes = null;
            HttpResponse httpResponse;

            byte[] result = null;

            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);

                if (cookies != null)
                {
                    for (int i = 0; i < cookies.Length; i++)
                    {
                        request.Headers.Add(cookies[i].name, cookies[i].value);
                    }
                }


                //以下是发送的http头，随便加，其中referer挺重要的，有些网站会根据这个来反盗链  

                //禁止重定向
                request.AllowAutoRedirect = false;

                //保持连接
                request.KeepAlive = true;

                //上面的http头看情况而定，但是下面俩必须加  
                request.ContentType = "application/x-www-form-urlencoded";

                //提交请求方式
                request.Method = method;
                if (!string.IsNullOrEmpty(postData))
                {
                    //postDataStr即为发送的数据  
                    bytes = encoding.GetBytes(postData);
                    request.ContentLength = bytes.Length;

                    //初始化请求数据流
                    requestStream = request.GetRequestStream();
                    requestStream.Write(bytes, 0, bytes.Length);
                }

                //获取返回数据
                response = (HttpWebResponse)request.GetResponse();
                responseStream = response.GetResponseStream();
                streamReader = new StreamReader(responseStream, encoding);

                result = ConvertStreamToByteBuffer(responseStream);
                string resultStr = encoding.GetString(result);

                if (resultStr.IndexOf("ID_LoginFormMark") > -1)
                {
                    httpResponse = new HttpResponse(false, "timeout");
                }
                else
                {
                    httpResponse = new HttpResponse(true, null, null, null, result);
                }
            }
            catch (Exception e)
            {
                httpResponse = new HttpResponse(false, e.Message);
            }
            finally
            {
                bytes = null;
                //关闭连接
                if (streamReader != null) streamReader.Close();
                if (responseStream != null) responseStream.Close();
                if (requestStream != null) requestStream.Close();
            }
            return httpResponse;
        }

        /// <summary>
        /// ConvertStreamToByteBuffer：把给定的文件流转换为二进制字节数组。
        /// </summary>
        public static byte[] ConvertStreamToByteBuffer(System.IO.Stream stream)
        {
            int b1;
            System.IO.MemoryStream resultStream = new System.IO.MemoryStream();
            while ((b1 = stream.ReadByte()) != -1)
            {
                resultStream.WriteByte(((byte)b1));
            }
            return resultStream.ToArray();

        }

        /// <summary>
        /// 获取所有Cookie
        /// </summary>
        public static List<Cookie> GetAllCookies(CookieContainer cc)
        {
            List<Cookie> lstCookies = new List<Cookie>();
            Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
                BindingFlags.NonPublic | BindingFlags.GetField |
                BindingFlags.Instance, null, cc, new object[] { });
            foreach (object pathList in table.Values)
            {
                SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
                    BindingFlags.NonPublic | BindingFlags.GetField
                    | BindingFlags.Instance, null, pathList, new object[] { });
                foreach (CookieCollection colCookies in lstCookieCol.Values)
                    foreach (Cookie c in colCookies) lstCookies.Add(c);
            }
            return lstCookies;
        }
    }
}
